<template>
  <a-modal :title="title" :after-close="reset" @ok="submit">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ style: { width: '80px' } }"
    >
      <a-form-item name="account" label="用户名">
        <a-input v-model:value="form.account" placeholder="请输入" />
      </a-form-item>
      <a-form-item v-if="passwordVisible" name="pwd" label="密码">
        <a-input-password v-model:value="form.pwd" placeholder="请输入" />
      </a-form-item>
      <a-form-item name="realName" label="管理员姓名">
        <a-input v-model:value="form.realName" placeholder="请输入" />
      </a-form-item>
      <a-form-item name="phone" label="手机号">
        <a-input v-model:value="form.phone" placeholder="请输入" />
      </a-form-item>
      <a-form-item name="roles" label="角色">
        <a-select
          v-model:value="form.roles"
          mode="multiple"
          placeholder="请选择"
          max-tag-count="responsive"
          :field-names="{ label: 'roleName', value: 'id' }"
          :options="roleOptions"
        />
      </a-form-item>
      <a-form-item name="status" label="状态">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="true"> 启用 </a-radio>
          <a-radio :value="false"> 禁用 </a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { getDeptTree, getRoleList } from '@/api/sys';
import { adminAddup, adminInfo } from '@/api/user';
import { User, type IUser } from '@/types/user';
import { validReg } from '@/utils/validate';
import { split } from 'lodash-es';

const props = withDefaults(defineProps<{
  data: Partial<IUser>
}>(),{
})
const title = computed(() => props.data.id ? '编辑' : '新增')
const { formRef, submit, close } = useDialog({ validCallback: save })

let form = $ref(new User())
let passwordVisible = $ref(true)
watchEffect(() => {
  passwordVisible = true
  if (props.data.id) {
    adminInfo(props.data.id).then(user => {
      let {roles,...temp} = user
      form.setProps(temp)
      form.roles  = user.roles?user.roles.split(',').map(e=>e*1):[]
    })
    passwordVisible = false
  }
})

const rules = {
  account: [validReg('required', '请输入用户名')],
  pwd: [validReg('required', '请输入密码')],
  phone: [validReg('phone', '手机号有误')],
  roles:[validReg('required', '值不能为空')],
}

onMounted(() => {

  getRoleOptions()
})
const emit = defineEmits(['change'])
function save() {
  let {roles} = form
 let role = roles.join()
  adminAddup({...form,roles:role}).then(() => {
    AntMessage.success('保存成功')
    close()
    emit('change')
  })
}
let roleOptions = $ref([])
function getRoleOptions() {
  getRoleList().then(res => {
    roleOptions = res.list
  })
}

function reset() {
  form = new User()
}
</script>

<style lang="less"></style>
